package com.jwater.core.net;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jwater.io.netty.util.concurrent.DefaultThreadFactory;
import jwater.org.springframework.util.StringUtils;
/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class NetExecutorUtils {
	protected static Logger logger = LoggerFactory.getLogger(NetExecutorUtils.class);

	public static int maxPoolSize;

	public static ExecutorService executorService = null;

	static {
		try {
			String size = System.getProperty("NET_MAX_POOL_SIZE");
			if (StringUtils.isEmpty(size)) {
				maxPoolSize = Runtime.getRuntime().availableProcessors() * 2;
				maxPoolSize = maxPoolSize < 8 ? 8 : maxPoolSize;
				maxPoolSize = maxPoolSize > 16 ? 16 : maxPoolSize;
			} else {
				maxPoolSize = Integer.parseInt(size);
			}
			executorService = new ThreadPoolExecutor(maxPoolSize, maxPoolSize, 60L, TimeUnit.SECONDS,
					new LinkedBlockingQueue<Runnable>(500), new DefaultThreadFactory("NetExecutor"),
					new CallerRunsPolicy());
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
	}

	public static void execute(Runnable command) {
		executorService.execute(command);
	}

	public static void close() {
		executorService.shutdownNow();
	}
}
